package cn.zjh.basic.service.impl;

import cn.zjh.basic.dto.SmsDto;
import cn.zjh.basic.constant.VerifyCodeConstants;
import cn.zjh.basic.exception.BusinessException;
import cn.zjh.basic.service.IVerifyCodeService;
import cn.zjh.basic.util.SmsUtil;
import cn.zjh.basic.util.StrUtils;
import cn.zjh.basic.util.VerifyCodeUtils;
import cn.zjh.user.domain.User;
import cn.zjh.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public String getImageCode(String Key) {
        if (Key == null){
            throw new BusinessException("key无效");
        }
        String code = StrUtils.getComplexRandomString(4);
        //MINUTES设置有效期三分钟
        redisTemplate.opsForValue().set(Key,code,3, TimeUnit.MINUTES);

        //code进行编码base64
        String verifyCode = VerifyCodeUtils.verifyCode(115, 43, code);

        //将base64位编码之后的字符串响应到controller
        return verifyCode;
    }

    @Override
    public void sentSmsCode(SmsDto smsDto) {

        //空置校检
        //获取前端传过来的值
        String phone = smsDto.getPhone();
        System.out.println(phone+"phone");
        String smsCode = smsDto.getImageCode();
        String smsCodeKey = smsDto.getImageCodeKey();

        System.out.println("图形验证码"+smsCode);

        if (StringUtils.isEmpty(phone)){
            throw new BusinessException("手机号码不能为空！！！");
        }
        if (StringUtils.isEmpty(smsCode)){
            throw new BusinessException("请重新刷新获取图形验证码！！！");
        }
        if (StringUtils.isEmpty(smsCodeKey)){
            throw new BusinessException("图形验证码不能为空！！");
        }

        //校检图形验证码是否过期
        Object codeKey = redisTemplate.opsForValue().get(smsCodeKey);
        if (codeKey == null){
            throw new BusinessException("验证码已过期，请重新获取！！");
        }
        //校检图形验证码是否正确
        if (!codeKey.toString().equalsIgnoreCase(smsCode)){
            throw new BusinessException("图形验证码错误，请重新输入！！");
        }
        //校检注册的手机号是否重复
        User onePhone = userMapper.findOnePhone(phone);
        if (onePhone != null){
            throw new BusinessException("该手机号已经被注册，请输入新的手机号！");
        }

        Object codes = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);

        String code = null;
        if (codes != null){
            String codeStr = (String)codes;
            String time = codeStr.split(":")[1];//分割字符串
            long intervalTime = System.currentTimeMillis() - Long.valueOf(time);
            if (intervalTime <= 1*60*1000){
                throw new BusinessException("请勿重复发送");
            }else {
                code = codeStr.split(":")[0];
            }
        }else {
            code = StrUtils.getComplexRandomString(4);
        }

        String msgCode = code + ":" + System.currentTimeMillis();

        //将验证码数据添加到redis
        redisTemplate.opsForValue().set(
                VerifyCodeConstants.REGISTER_CODE_PREFIX+phone,
                msgCode,
                3,
                TimeUnit.MINUTES);//验证码存在三分钟

     //   SmsUtil.sendSms(phone,"你的验证码为："+code+"这是唯一的验证");


        System.out.println("验证码是：" +code);

    }

    @Override
    public void binderSmsCode(SmsDto smsDto) {

        String phone = smsDto.getPhone();

        //校验 - 空值校验
        if(StringUtils.isEmpty(phone)){
            throw new BusinessException("手机号码不能为空!!!");
        }

        //获取手机验证码 - 判断是否过期
        Object redisSmsCode = redisTemplate.opsForValue().get(VerifyCodeConstants.BINDER_CODE_PREFIX + phone);
        String code = null;
        if(redisSmsCode == null){//第一次发送 或者 手机验证码过期了
            //过期了就用新的验证码
            code = StrUtils.getComplexRandomString(6);
        }else{//没有过期
            //验证是否过了重发时间
            //以前保存的时间
            long redisTime = Long.parseLong(redisSmsCode.toString().split(":")[1]);
            //现在的时间
            long nowTime = System.currentTimeMillis();
            //没有过期 - 判断是否过了重发时间
            if((nowTime-redisTime)<1*60*1000){//没有过重发时间
                throw new BusinessException("请勿重复获取验证码!!!");
            }else{
                //没有过期就用以前的验证码
                code = redisSmsCode.toString().split(":")[0];
            }
        }

        //7.将验证码存入redis：
        //刷新了过期时间
        redisTemplate.opsForValue().set(VerifyCodeConstants.BINDER_CODE_PREFIX + phone,code+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);

        //8.调用SmsUtils发送短信
        //SmsUtil.sendSms(phone,"手机验证码为：" + code + ",请在3分钟内使用!!!");
        System.out.println("手机验证码为：" + code + ",请在3分钟内使用!!!");
    }

}

